# -*- coding: utf-8 -*-
from datetime import timedelta, datetime, date
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor
from jms.dm.dm_star_staff_rnk_detail_dt import jms_dm__dm_star_staff_rnk_detail_dt


def doris_partitions_str():
    """
    获取获得一个月中的最后一天
    :param any_day: 任意日期
    :return: string
    """
    today = date.today()
    # 计算昨天的日期
    yesterday = today - timedelta(days=1)
    next_month = yesterday.replace(day=28) + timedelta(days=4)  # this will never fail
    last_day = next_month - timedelta(days=next_month.day)
    first_day_of_month = last_day.replace(day=1)
    date_range = [first_day_of_month + timedelta(days=x) for x in range((last_day - first_day_of_month).days + 1)]
    doris_partitions_str = ','.join(['p' + str(date.strftime('%Y%m%d')) for date in date_range])
    return doris_partitions_str


partitions_str = doris_partitions_str()


label = f"dm_star_staff_rnk_detail_dt_{int(time())}"
timeout = timedelta(minutes=60).seconds
doris_jms_dm__dm_star_staff_rnk_detail_dt = RichSqlSensor(
    task_id='doris_jms_dm__dm_star_staff_rnk_detail_dt',
    pool='broker_load_pool',
    email=['matthew.xiong@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    task_concurrency=1,
    conn_id='doris',
    pre_sql=f"""
	TRUNCATE TABLE jms_dm.dm_star_staff_rnk_detail_dt PARTITION (
		{partitions_str}
	);
    LOAD LABEL jms_dm.{label} (
        DATA INFILE(
        "hdfs://{{{{var.value.hadoop_namespace}}}}/dw/hive/jms_dm.db/external/dm_star_staff_rnk_detail_dt/dt={{{{ execution_date | cst_ds }}}}/*"
        )
    INTO TABLE dm_star_staff_rnk_detail_dt
    FORMAT AS 'PARQUET'
    ) WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
    PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dm WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dm WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120),
)

doris_jms_dm__dm_star_staff_rnk_detail_dt << jms_dm__dm_star_staff_rnk_detail_dt
